/**
 * Created by wang on 2016-8-30.
 * 通达信本地服务
 */
define(['angular'], function (angular) {
    "use strict";
    var factory = function ($q, $state, $rootScope, CommonService, GCS_BASE_PATH, LocalCacheService, WebService, ConcernService) {
        return {
            isTDX: function () { //环境监测
                return LocalCacheService.getAppContextName() == "gcs_tdx" || (LocalCacheService.getAppContextName() == '' && typeof TDXInterface != 'undefined');
            },
            sysSet: function () {
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenID': 'Me'}
                }, function (obj) {
                    deferred.resolve(obj);
                });
                return deferred.promise;
            },
            openDzht: function () {//电子合同
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenID': 'Stock.lcyw'}
                }, function (obj) {
                    deferred.resolve(obj);
                });
                return deferred.promise;
            },
            openYzzz: function () {//银证转账
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenID': 'Stock.yzyw.yzzz'}
                }, function (obj) {
                    deferred.resolve(obj);
                });
                return deferred.promise;
            },
            modifyPwd: function () {//修改密码
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenID': 'Stock.jysz'}
                }, function (obj) {
                    deferred.resolve(obj);
                });
                return deferred.promise;
            },
            logout: function () {//退出
                var deferred = $q.defer();
                TDXInterface.callFunc({"tdxFuncName": "tdxQuitTrade", "tdxFuncParam": ""}, function (obj) {
                    deferred.resolve(obj);
                });
                return deferred.promise;
            },
            loginGcs: function () { //登录
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxLoginTrade",
                    "tdxFuncParam": {'HostType': '0', 'SwitchFlag': '1'}
                }, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            changeActiveUser: function () { //活跃账户切换
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenID': 'ZHGL'}
                }, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            tdxShowBottomBar: function () { //显示通达信底部工具栏
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxBottomBarVisibility",
                    "tdxFuncParam": {'VisibilityFlag': '1'}
                }, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            tdxHideBottomBar: function () { //隐藏通达信底部工具栏
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxBottomBarVisibility",
                    "tdxFuncParam": {'VisibilityFlag': '0'}
                }, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            tdxTradeLocked: function () {
                var deferred = $q.defer();
                TDXInterface.callFunc({"tdxFuncName": "tdxIsTradeLocked", "tdxFuncParam": ""}, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            tdxRefreshPage: function () { //主动刷新触发
                var deferred = $q.defer();
                TDXInterface.callFunc({
                    "tdxFuncName": "tdxOpenNativeModule",
                    "tdxFuncParam": {'OpenAction': 'Refresh'}
                }, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            tdxTradeLockRefresh: function () {//重置锁定时间，配合tdxTradeLocked使用，如果tdxTradeLocked判断无需锁定，则调用重置锁定时间
                var deferred = $q.defer();
                TDXInterface.callFunc({"tdxFuncName": "tdxFlushJYLockTime", "tdxFuncParam": ""}, function (data) {
                    deferred.resolve(data);
                });
                return deferred.promise;
            },
            /**
             * 获取当前用户
             *  KHH ----------客户号
             Name ----------客户姓名
             ZJZH ----------资金账号
             HostType ----------账号类型（普通 0 信用 1 期货 2 港股 3 ）
             SessionID ----------连接的session
             */
            getActivePtUser: function () {
                var deferred = $q.defer();
                var timer=new Date().getTime();
                console.log('获取用户登录状态:'+timer);
                TDXInterface.callFunc({"tdxFuncName": "tdxEnumTradeAcc", "tdxFuncParam": ""}, function (data) {
                    timer=new Date().getTime();
                    console.log('获取用户登录状态:'+timer);
                    var result = JSON.parse(data.text);
                    var tdx_data = {};
                    if (result.length > 0) {
                        if (result[0].HostType == "0") {
                            tdx_data.KHH = result[0].KHH;
                            tdx_data.SessionID = result[0].SessionID;
                            deferred.resolve(tdx_data);
                        } else { //活跃账户不是普通账号
                            var isPt = false;
                            for (var i = 1; i < result.length; i++) {
                                if (result[i].HostType == "0") {
                                    tdx_data.KHH = result[i].KHH;
                                    tdx_data.SessionID = result[i].SessionID;
                                    isPt = true;
                                    break;
                                }
                            }
                            if (isPt) {
                                deferred.resolve(tdx_data);//获得普通账户
                            } else {
                                deferred.reject(-2);//没有登录普通账号
                            }
                        }
                    } else {
                        deferred.reject(-1);//没有登录
                    }
                });
                return deferred.promise;
            },
            loginTap: function (tdx_data, func, func_err) {
                var _this = this;
                var user = LocalCacheService.getUser();
                if (user && user.token && user.client_id == tdx_data.KHH) {
                    func();
                } else {
                    var params = {};
                    params.url = "/trade/user/login";
                    params.data = {
                        account_content: tdx_data.KHH,
                        password: '#PASSWORD#',
                        input_content: '1'
                    };
                    params.basePath = GCS_BASE_PATH;
                    params.isSendData = true;
                    params.isReject = true;
                    params.PasswordSessionID = tdx_data.SessionID;
                    var timer=new Date().getTime();
                    console.log("登录开始："+timer);
                    CommonService.ajax(params).then(function (data) {
                        timer=new Date().getTime();
                        console.log("登录结束："+timer);
                        LocalCacheService.removeUser();
                        var user = {};
                        user.token = data.token;
                        LocalCacheService.setUser(user);
                        WebService.getUserInfo().then(
                            function (result) {
                                timer=new Date().getTime();
                                console.log("获取用户信息："+timer);
                                LocalCacheService.setUser(result);
                                func();
                                //WebService.qryConduitInfo({mobile_tel: result.mobile_tel}).then(function (data) {
                                //    if (!CommonService.isStrEmpty(data.conduit_no)
                                //        && CommonService.isStrEmpty(LocalCacheService.getRecommendInfos())) {
                                //        LocalCacheService.setRecommendInfos(data.conduit_no);
                                //    }
                                //    func();
                                //}, function () {
                                //    _this.logout();
                                //    LocalCacheService.removeUser();
                                //    if(func_err){
                                //        func_err();
                                //    }else{
                                //        CommonService.showConfig({message: "获取用户信息失败"});
                                //    }
                                //    if ($state.current.name != 'tab.index') {
                                //        $state.go('tab.index');
                                //    }
                                //});
                            }, function (result) {
                                _this.logout();
                                LocalCacheService.removeUser();
                                if(func_err){
                                    func_err();
                                }else{
                                    CommonService.showConfig({message: "获取用户信息失败"});
                                }
                                if ($state.current.name != 'tab.index') {
                                    $state.go('tab.index');
                                }
                            }
                        );
                        //同步用户关注信息
                        params.cares_str = ConcernService.getConcernList();
                        WebService.syncUserCare(params);
                    }, function (result) {
                        _this.logout();
                        LocalCacheService.removeUser();
                        if(func_err){
                            func_err();
                        }else{
                            if (result.error_info == '客户状态异常') {
                                CommonService.showConfig({message: '账户状态异常'});
                            } else {
                                CommonService.showConfig({message: CommonService.getErrorInfo(result)});
                            }
                        }
                        if ($state.current.name != 'tab.index') {
                            $state.go('tab.index');
                        }
                    });
                }
            },
            checkUser: function (func) {
                var _this = this;
                _this.getActivePtUser().then(function (data) {
                    _this.loginTap(data, func, null);
                }, function (data) {
                    if (data == -1) {
                        LocalCacheService.removeUser();
                        _this.loginGcs().then(function () {
                            $rootScope.$broadcast('refresh','userInfoRefresh');//为ios触发主动刷新
                            _this.checkUser(func);
                        });
                    } else if (data == -2) {
                        CommonService.showConfirm({title: '提示', message: '需要登录普通交易账户，是否登录到普通交易账户？'}, function () {
                            if ($state.current.name != 'tab.index') {
                                LocalCacheService.removeUser();
                                $state.go('tab.index');
                            }
                        }, function () {
                            LocalCacheService.removeUser();
                            _this.loginGcs().then(function () {
                                _this.checkUser(func);
                            });
                        })
                    }
                    //else if(data == -3) {
                    //    LocalCacheService.removeUser();
                    //    CommonService.showConfirm({title:'提示',message:'需要指定当前账户为普通交易账户，是否切换到普通交易账户？'},function(){
                    //        if($state.current.name!='tab.index'){
                    //            $state.go('tab.index');
                    //        }
                    //    },function(){
                    //        _this.changeActiveUser().then(function(){
                    //            _this.checkUser(func);
                    //        });
                    //    })
                    //}
                })
            }
        }
    };

    factory.$inject = ['$q', '$state', '$rootScope', 'CommonService', 'GCS_BASE_PATH', 'LocalCacheService', 'WebService', 'ConcernService'];
    return factory;
});